<?php 
/**
 * @author Robert Hahn
 * @version 02/21/2011
 */
class SnapfacebookComponent extends Object	{
	
	var $name = 'Snapfacebook'; 
	var $components = array('Session', 'Cookie'); 
	var $options = array();
	var $user = array();
	
	function initialize(&$controller) {
		$this->controller = &$controller;
	}
	/**
	 * business as usual - set the options
	 * @param array $options
	 */
	function setOptions( $options=array() )	{
		if (!defined("FACEBOOK_APP_ID") && isset($options['appid']))
		define('FACEBOOK_APP_ID', $options['appid']);
		if (!defined("FACEBOOK_SECRET_ID") && isset($options['secretkey']))
		define('FACEBOOK_SECRET_ID', $options['secretkey']);
		
		if (!is_array($options)) return;
		foreach($options as $key => $value)	
			$this->options[ $key ] = $value;
	}
	
	/**
	 * will check if the url was called by facebook; in case the facebook user will be grabbed
	 * @return object facebook account given by the facebook oauth request with our access token
	 */
	function onLoginCallback()	{
		if (isset($this->controller->params['url']) && isset($this->controller->params['url']['code']))	{
			App::import('Core', 'HttpSocket');
			// lets grab the access token
			$root = "http://".$_SERVER['HTTP_HOST'].str_replace('webroot/index.php', '', $_SERVER['PHP_SELF']);
			$url = "https://graph.facebook.com/oauth/access_token?client_id=".FACEBOOK_APP_ID."&redirect_uri=$root&type=client_cred&client_secret=".FACEBOOK_SECRET_ID."&code=".$this->controller->params['url']['code'];
			$HttpSocket = new HttpSocket();
			$accessToken = $HttpSocket->get($url); // this is it
			$code = explode('|', $this->controller->params['url']['code']);
			$code = explode('-', $code[0]);
			$fbuid= $code[count($code)-1]; // grab the current facebook userid
			$url = "https://graph.facebook.com/$fbuid?".$accessToken; // with accesstoken request the user data
			$this->Session->write('accesstoken', $accessToken);
			$user = $HttpSocket->get($url);  
			$facebookUser = json_decode($user); // thats the user as json string
			return $facebookUser; // return the user
		}
		return null; // ups, that wasnt a valid facebook request
	}
}
?>